<?php

namespace App\Http\Controllers;

use App\Models\Topic;
use App\Http\Requests\StoreTopicRequest;
use App\Http\Requests\UpdateTopicRequest;
use App\Http\Resources\TopicResource;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;

class TopicController extends Controller implements HasMiddleware
{
    public static function middleware(){
        // 当前所有的方法都需要登录验证
        // return ['auth'];
        return [
            new Middleware('auth',except:['index','show'])
        ];
    }
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //返回所有的数据->关联user(当前用户)->分页(用户不传row参数就默认10条)
        // return Topic::all();
        return TopicResource::collection(Topic::with('user')->paginate(request('row', '10')));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreTopicRequest $request)
    {
        Gate::authorize('create', Topic::class); // 拦截器策略
        // 新增一条帖子
        $topic = new Topic();
        $topic->user_id = Auth::id();
        $topic->title = $request->input('title');
        $topic->content = $request->input('content');
        $topic->save();
        return $topic;
    }

    /**
     * 获取一条帖子
     */
    public function show(Topic $topic)
    {
        return new TopicResource($topic);
    }
    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateTopicRequest $request, Topic $topic)
    {
        // 修改帖子
        Gate::authorize('update', Topic::class);
        $topic->fill($request->all());
        $topic->save();
        return new TopicResource($topic);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Topic $topic)
    {
        // 删除帖子
        Gate::authorize('delete', $topic);
        $topic->delete();
        return response(null, 204);
    }
}
